package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper,Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;
    @Override
    public void saveWithDishes(SetmealDto setmealDto) {
        //先保存套餐信息
        this.save(setmealDto);
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes().stream().map((item) ->{
            //设置套餐id
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        //保存套餐菜品信息
        setmealDishService.saveBatch(setmealDishList);
    }

    @Override
    public void updateWithDishes(SetmealDto setmealDto) {
        //先修改套餐信息
        this.updateById(setmealDto);

        //删除套餐关联的所有菜品信息
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,setmealDto.getId());
        setmealDishService.remove(queryWrapper);
        //更新关联的菜品信息
        List<SetmealDish> setmealDtoList = setmealDto.getSetmealDishes().stream().map((item) ->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDtoList);
    }

    @Override
    public void deleteWithDishes(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> query = new LambdaQueryWrapper<>();
        query.in(Setmeal::getId,ids).eq(Setmeal::getStatus,1);
        int count = this.count(query);
        if(count>0){
            throw new CustomException("正在售卖中的套餐无法删除，请先停售");
        }
        //删除套餐
        this.removeByIds(ids);
        //移除套餐关联的菜品信息
        setmealDishService.removeByIds(ids);
    }
}
